import { Response } from 'express';
import { ApiResponse } from '../types';

/**
 * 成功响应
 */
export const successResponse = <T>(
  res: Response,
  data: T,
  message: string = '操作成功',
  code: number = 200
): Response => {
  const response: ApiResponse<T> = {
    code,
    message,
    data,
    timestamp: new Date().toISOString()
  };
  return res.status(code).json(response);
};

/**
 * 错误响应
 */
export const errorResponse = (
  res: Response,
  message: string = '操作失败',
  code: number = 400,
  data?: any
): Response => {
  const response: ApiResponse = {
    code,
    message,
    data,
    timestamp: new Date().toISOString()
  };
  return res.status(code).json(response);
};

/**
 * 分页响应
 */
export const paginatedResponse = <T>(
  res: Response,
  items: T[],
  total: number,
  page: number,
  limit: number,
  message: string = '获取成功'
): Response => {
  const totalPages = Math.ceil(total / limit);
  const data = {
    items,
    total,
    page,
    limit,
    totalPages
  };
  return successResponse(res, data, message);
};

/**
 * 格式化成功响应数据（不直接发送响应）
 */
export const formatSuccessResponse = <T>(
  message: string = '操作成功',
  data?: T,
  code: number = 200
): ApiResponse<T> => {
  return {
    code,
    message,
    data,
    timestamp: new Date().toISOString()
  };
};